package controller.PurchaseTable;

import entity.MsgResult;
import entity.goods;
import entity.purchase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.AddPurchaseService;
import service.SelectGoodsByIdService;
import service.UpdateGoodsService;

import java.util.Date;

@Controller
public class AddPurchaseController {
    @Autowired
    private AddPurchaseService addPurchaseService;
    @Autowired
    private UpdateGoodsService updateGoodsService;

    @Autowired
    private SelectGoodsByIdService selectGoodsByIdService;

    @RequestMapping("/addPurchase")
    @ResponseBody
    public MsgResult addPurchase(purchase purchase){
        MsgResult msgResult = new MsgResult();
        Date currDate = new Date();
        //获取当前时间
        purchase.setPurchaseDate(currDate);
        //根据id查询要更新数据的商品
        goods good = selectGoodsByIdService.selectGoodsById(purchase.getGoodsId());
        //创建对象
        goods goods = new goods();
        goods.setGoodsId(purchase.getGoodsId());
        //库存更新
        int newNum = (int) (good.getStockNum() + purchase.getNum());
        goods.setStockNum((long) newNum);
        goods.setNumUpdateDate(currDate);
        updateGoodsService.updateGoods(goods);
        boolean b = addPurchaseService.addPurchase(purchase);
        if(b){
            msgResult.setFlag(1);
            msgResult.setMsg("进货成功");
            return msgResult;
        }
        msgResult.setFlag(0);
        msgResult.setMsg("进货失败");
        return msgResult;
    }
}
